<?php
/**
 * Created by PhpStorm.
 * User: qingmu-523
 * Date: 2018/10/22
 * Time: 11:45
 */

namespace App\Command;

use Carbon\Carbon;
use PDO;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class CreateI217XmlSalesReturn extends BaseCommand
{
    protected function configure()
    {
        $endTime = Carbon::now("Asia/Shanghai");
        $startTime = Carbon::now("Asia/Shanghai")->subMinute(10);
        $this
            ->setName('app:create-i217-sales-return')
            ->setDescription('创建i217订单的退货xml，需要订单已经发货')
            ->setHelp("创建i217订单的退货xml，需要订单已经发货，即已经生成i216")// configure an argument / 配置一个参数
            ->addOption("tid", '', InputOption::VALUE_OPTIONAL, "为该tid的订单创建i217订单的退货xml，需要订单已经发货，即已经生成i216", 0)
            ->addOption("orderSn", '', InputOption::VALUE_OPTIONAL, "为该订单号创建i217订单的退货xml，需要订单已经发货，即已经生成i216", 0)
            ->addOption("startTime", "", InputOption::VALUE_REQUIRED, "截取订单开始时间，默认查找前十分钟", $startTime)
            ->addOption("endTime", "", InputOption::VALUE_REQUIRED, "截取订单结束时间，默认查找前十分钟", $endTime);
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $tid = $input->getOption('tid');
        $orderSn = $input->getOption('orderSn');
        $messageDateTime = date('Ymd') . "T" . date("Hi") . "+0800";
        $this->redis->setnx("unqiue:i216",10000);
        $startTime = $input->getOption('startTime');
        $endTime = $input->getOption('endTime');
        if ($tid != 0) {
            $unqiue =  $this->redis->incr("unqiue:i217");
            $infos = $this->omsdb->query("SELECT wms.sn,o.order_sn,o.channel_order_id,o.shipping_id,o.invoice_no,wms.id as ticket_id
            FROM `wms_tickets` as `wms`
            left join `order_info` as `o`
            on `wms`.`original_sn` = `o`.`order_sn`
            WHERE  wms.status_notify=:status_notify and wms.type_code = :type_code and o.channel_order_id = :channel_order_id limit 0,1", [ //wms.time_create >= :time_create and
                    ":status_notify" => -3,
                    ":type_code" => "XS",
                    ":channel_order_id" => $tid,
                ]
            )->fetchAll(PDO::FETCH_ASSOC);
            $this->create_file($infos,$messageDateTime,$unqiue);
            exit;

        } elseif ($orderSn != 0) {
            $unqiue =  $this->redis->incr("unqiue:i216");
            $infos = $this->omsdb->query("SELECT wms.sn,o.order_sn,o.channel_order_id,o.shipping_id,o.invoice_no,wms.id as ticket_id
            FROM `wms_tickets` as `wms`
            left join `order_info` as `o`
            on `wms`.`original_sn` = `o`.`order_sn`
            WHERE  wms.status_notify=:status_notify and wms.type_code = :type_code and o.order_sn = :order_sn limit 0,1", [ //wms.time_create >= :time_create and
                    ":status_notify" => -3,
                    ":type_code" => "XS",
                    ":order_sn" => $orderSn,
                ]
            )->fetchAll(PDO::FETCH_ASSOC);
            $this->create_file($infos,$messageDateTime,$unqiue);
            exit;
        } else {
            for ($page = 1; ; $page++) {
                echo memory_get_usage() . "    使用内存\n";
                $unqiue =  $this->redis->incr("unqiue:i216");
                $messageDateTime = date('Ymd') . "T" . date("Hi") . "+0800";
                $pageSize = 1000;
                $limit = " limit " . ($page - 1) * $pageSize . "," . $pageSize;

                $infos = $this->omsdb->query("SELECT wms.sn,o.order_sn,o.channel_order_id,o.shipping_id,o.invoice_no,wms.id as ticket_id
                FROM `wms_tickets` as `wms`
                left join `order_info` as `o`
                on `wms`.`original_sn` = `o`.`order_sn`
                WHERE  wms.status_notify=:status_notify and wms.type_code = :type_code and wms.time_create >= :startTime and wms.time_create <= :endTime   $limit", [ //wms.time_create >= :time_create and
                        // ":time_create" => '2018-09-28 09:00:26',
                        ":status_notify" => -1,
                        ":type_code" => "XS",
                        ":startTime" => $startTime,
                        ":endTime" => $endTime,
                    ]
                )->fetchAll(PDO::FETCH_ASSOC);
                if (!$infos) {
                    echo('没有查询到数据');
                    exit;
                }
                $returnOrderXml = '';
                foreach ($infos as $info) {
                    //获取订单商品数据
                    $goods_infos = $this->omsdb->query("SELECT * from wms_tickets_goods where ticket_id = :ticket_id", [
                        ":ticket_id" => $info['ticket_id']])->fetchAll(PDO::FETCH_ASSOC);
                    // var_dump($goods_infos);
                    foreach ($goods_infos as $goods) { ////'.$goods['number_expected'].'
                        $order_line = $this->omsdb->query("SELECT order_line_id from hm_order_sn_line where order_sn = :order_sn and sku_sn = :sku_sn", [
                            ":order_sn" => $info['order_sn'],
                            ":sku_sn" => $goods['goods_sku_sn'],
                        ])->fetchAll(PDO::FETCH_ASSOC);
                        foreach ($order_line as $order_line_item){
                            $returnOrderXml .= '
                            <returnOrder>
                                <siteId>W148</siteId>
                                <countryCode>CN</countryCode>
                                <returnReceiptDateTime>' . $messageDateTime . '</returnReceiptDateTime>
                                <salesOrderNumber>' . $info['channel_order_id'] . '</salesOrderNumber>
                                <consignmentNumber>' . $info['sn'] . '</consignmentNumber>
                                <wmsReturnOrderNumber>1</wmsReturnOrderNumber>
                                <orderVersion>T</orderVersion>
                                <returnType>R</returnType>
                                <prepaidLabel>0</prepaidLabel>
                                <declarationMismatch>0</declarationMismatch>
                                <invoiceDocument>0</invoiceDocument>
                                <referenceField1>'.$info['order_sn'].'</referenceField1>
                                <referenceField2/>
                                <returnOrderLines>
                                <returnOrderLine>
                                    <salesOrderLineItemNumber>'.$order_line_item['order_line_id'].'</salesOrderLineItemNumber>
                                    <consignmentLineItemNumber>'.$unqiue.'</consignmentLineItemNumber>
                                    <wmsReturnedOrderLineItemNumber>00001</wmsReturnedOrderLineItemNumber>
                                    <sku>'.$goods['goods_sku_sn'].'</sku>
                                    <season>201808</season>
                                    <countryOfOrigin>BD</countryOfOrigin>
                                    <hmOrder>130855</hmOrder>
                                    <customerReasonCode>3</customerReasonCode>
                                    <quantity>1</quantity>
                                </returnOrderLine>
                                </returnOrderLines>
                            </returnOrder>
                            ';
                        }
                        // var_dump($order_line);

                    }
                }

// $date = microtime_format('YmdHisx',microtime_float());
                $date = date("YmdHis");
// $doc->save("./xml/I216_LF01_QM_00067353_000_$date.xml");
                $file = "I217_LF01_QM_000{$unqiue}_000_$date";
                $xml =
                    '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
                        <x:businessTransaction xmlns:x="urn:hm:wms:returns:xsd:1.2" xmlns:shared_common="urn:hm:shared:shared_common:xsd:1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0" >
                          <messageMetadata>
                            <messageDateTime>'.$messageDateTime.'</messageDateTime>
                            <sourceSystem>LF01 WMS</sourceSystem>
                            <receivingSystem>HM GOEP</receivingSystem>
                            <messageType>Customer Return</messageType>
                            <messageId/>
                            <originalFileName>WMSSHP_' . $file . '.txt</originalFileName>
                          </messageMetadata>
                          <returnOrders>
                            '.$returnOrderXml.'
                          </returnOrders>
                        </x:businessTransaction>
                        ';
                $content = str_replace("\n", "", $xml);

                file_put_contents("./xml/{$file}.xml", $content, FILE_USE_INCLUDE_PATH);
                unset($infos);
                var_dump("./xml/{$file}.xml");
            }
        }

    }

    function create_file($infos,$messageDateTime,$unqiue)
    {
        if (!$infos) {
            echo('没有查询到数据');
            exit;
        }
// var_dump($oms_db->last());
        // echo '数据';
        // var_dump($infos);
        $returnOrderXml = '';
        foreach ($infos as $info) {
            //获取订单商品数据
            $goods_infos = $this->omsdb->query("SELECT * from wms_tickets_goods where ticket_id = :ticket_id", [
                ":ticket_id" => $info['ticket_id']])->fetchAll(PDO::FETCH_ASSOC);
            // var_dump($goods_infos);
            foreach ($goods_infos as $goods) { ////'.$goods['number_expected'].'
                $order_line = $this->omsdb->query("SELECT order_line_id from hm_order_sn_line where order_sn = :order_sn and sku_sn = :sku_sn", [
                    ":order_sn" => $info['order_sn'],
                    ":sku_sn" => $goods['goods_sku_sn'],
                ])->fetchAll(PDO::FETCH_ASSOC);
                var_dump($this->omsdb->last());
                var_dump($order_line);
                $returnOrderXml .= '
            <returnOrder>
                <siteId>W148</siteId>
                <countryCode>CN</countryCode>
                <returnReceiptDateTime>' . $messageDateTime . '</returnReceiptDateTime>
                <salesOrderNumber>' . $info['channel_order_id'] . '</salesOrderNumber>
                <consignmentNumber>' . $info['sn'] . '</consignmentNumber>
                <wmsReturnOrderNumber>1</wmsReturnOrderNumber>
                <orderVersion>T</orderVersion>
                <returnType>R</returnType>
                <prepaidLabel>0</prepaidLabel>
                <declarationMismatch>0</declarationMismatch>
                <invoiceDocument>0</invoiceDocument>
                <referenceField1>'.$info['order_sn'].'</referenceField1>
                <referenceField2/>
                <returnOrderLines>
                <returnOrderLine>
                    <salesOrderLineItemNumber>'.$order_line[0]['order_line_id'].'</salesOrderLineItemNumber>
                    <consignmentLineItemNumber>'.$unqiue.'</consignmentLineItemNumber>
                    <wmsReturnedOrderLineItemNumber>00001</wmsReturnedOrderLineItemNumber>
                    <sku>'.$goods['goods_sku_sn'].'</sku>
                    <season>201808</season>
                    <countryOfOrigin>BD</countryOfOrigin>
                    <hmOrder>130855</hmOrder>
                    <customerReasonCode>3</customerReasonCode>
                    <quantity>1</quantity>
                </returnOrderLine>
                </returnOrderLines>
            </returnOrder>
            ';
            }
        }

        $date = date("YmdHis");
        $file = "I217_LF01_QM_000{$unqiue}_000_$date";

        $xml =
            '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
            <x:businessTransaction xmlns:x="urn:hm:wms:returns:xsd:1.2" xmlns:shared_common="urn:hm:shared:shared_common:xsd:1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0" >
              <messageMetadata>
                <messageDateTime>'.$messageDateTime.'</messageDateTime>
                <sourceSystem>LF01 WMS</sourceSystem>
                <receivingSystem>HM GOEP</receivingSystem>
                <messageType>Customer Return</messageType>
                <messageId/>
                <originalFileName>WMSSHP_' . $file . '.txt</originalFileName>
              </messageMetadata>
              <returnOrders>
                '.$returnOrderXml.'
              </returnOrders>
            </x:businessTransaction>
            ';
        $content = str_replace("\n", "", $xml);

        file_put_contents("./xml/{$file}.xml", $content, FILE_USE_INCLUDE_PATH);
        unset($infos);
        var_dump("./xml/{$file}.xml");
    }
}